import LC from 'leancloud-storage'
const login = (username, password) => {
  return new Promise((resolve, reject) => {
    LC.User.logIn(username, password)
      .then(user => {
        console.log(user)
        resolve(user)
        //  resolve()返回成功之后的结果，被 then()接收
      }, error => {
        console.log(error)
        reject(error)
        //  reject() 返回失败的信息， 被catch()接收
      }).catch(error => {
        reject(error)
      })
  })
}
const isLoggedIn = () => {
  const currentUser = LC.User.current()
  if (currentUser) {
    console.log(currentUser)
    return currentUser
  }
  return false
}
const logout = () => {
  LC.User.logOut()
  console.log(LC.User.current())
}
const signUp = (username, password, email = '') => {
  const user = new LC.User()
  user.setUsername(username)
  user.setPassword(password)
  if (email) {
    user.setEmail(email)
  }
  return new Promise((resolve, reject) => {
    user.signUp()
      .then(user => {
        console.log('注册成功')
        resolve(user)
      }, error => {
        console.log('注册不成功：', error)
        reject(error)
      })
      .catch(error => {
        console.log('注册过程中出现意外： ', error)
        reject(error)
      })
  })
}
export default {
  login,
  isLoggedIn,
  logout,
  signUp
}
